<template>
	<div class="container">
		<h2>{{ id ? '修改' : '新增' }}委托人</h2>
		<h3 style="margin: 10px 0;">
			<b>基础信息</b>
		</h3>
		<a-form ref="formRef" :label-col="{ style: { width: '80px' } }" :rules="formRules" :model="formState" layout="vertical" @finish="save">
			<a-row :gutter="20">
				<a-col :span="8">
					<a-form-item label="姓名" name="fullname">
						<a-input v-model:value="formState.fullname" :disabled="isSupplier" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="手机号" name="mobile" @change="changeMobile(formState.mobile)">
						<a-input v-model:value="formState.mobile" placeholder="可用于账号登录" :disabled="isSupplier" />
					</a-form-item>
				</a-col>
			</a-row>
			<!--			<a-row :gutter="20">-->
			<!--				<a-col :span="8">-->
			<!--					<a-form-item label="密码" name="password">-->
			<!--						<a-input-password v-model:value="formState.password" autocomplete="off" />-->
			<!--					</a-form-item>-->
			<!--				</a-col>-->
			<!--				<a-col :span="8">-->
			<!--					<a-form-item label="重复密码" name="confirm_password">-->
			<!--						<a-input-password v-model:value="formState.confirm_password" autocomplete="off" />-->
			<!--					</a-form-item>-->
			<!--				</a-col>-->
			<!--			</a-row>-->
			<a-row :gutter="20">
				<a-col :span="8">
					<a-form-item label="账户状态" name="status">
						<a-radio-group v-model:value="formState.status" :disabled="isSupplier">
							<a-radio :value="1">正常</a-radio>
							<a-radio :value="0">冻结</a-radio>
						</a-radio-group>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="供应商" name="parent_id">
						<a-select v-model:value="formState.parent_id" :show-search="true" placeholder="选择供应商名称" :options="supplierOptions" option-filter-prop="label" allow-clear :disabled="isSupplier" @change="changeSupplier"></a-select>
					</a-form-item>
				</a-col>
			</a-row>
			<h3 style="margin: 10px 0;">
				<b>绑定项目</b>
				<a-button size="small" class="ml-10" type="primary" ghost @click="addProject">+</a-button>
			</h3>
			<a-row v-for="(item, index) in formState.projects" :key="index" :gutter="20">
				<a-col :span="8">
					<a-form-item label="项目" :name="['projects', index, 'project_id']" :rules="[{ required: true, message: '请选择项目', trigger: 'blur' }]">
						<a-select v-model:value="item.project_id" :show-search="true" placeholder="请选择项目" :options="projectOptions" option-filter-prop="label" @change="changeProject(item)"></a-select>
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-row :gutter="20">
						<a-col v-show="false" :span="10">
							<a-form-item label="有效期" :name="['projects', index, 'is_permanent']" :rules="[{ required: true, message: '请选择有效期类型', trigger: 'blur' }]">
								<a-radio-group v-model:value="item.is_permanent" name="is_permanent" disabled @change="changePermanent(item, index)">
									<a-radio :value="1">长期有效</a-radio>
									<a-radio :value="0">自定义</a-radio>
								</a-radio-group>
							</a-form-item>
						</a-col>
						<a-col :span="14">
							<a-form-item v-show="item.is_permanent === 0" label="授权有效期" :name="['projects', index, 'date_range']" :rules="item.is_permanent === 0 ? [{ required: true, message: '请选择授权有效期', trigger: 'blur', type: 'array' }] : []">
								<a-range-picker v-model:value="item.date_range" allow-clear value-format="YYYY-MM-DD" @change="changeDateRange(item)" />
							</a-form-item>
						</a-col>
						<a-col :span="10">
							<a-form-item label="委托书" :name="['projects', index, 'entrust_file_path']" :rules="[{ required: true, message: '请选择委托书', trigger: 'blur' }]">
								<a-upload v-model:file-list="item.entrust_file_path" name="upload" :action="`${baseURL}/contract/upload`" :show-upload-list="true" :headers="{ Authorization: `Bearer ${proxy.$cookies.get('token')}` }" :before-upload="beforeFileUpload(item)" @change="changeFileUpload(item, $event)">
									<a-button>
										<template v-if="item.fileUploading">
											<loading-outlined />上传中...
										</template>
										<template v-else>
											<import-outlined />上传附件
										</template>
									</a-button>
								</a-upload>
								<span style="color:#ccc">
									提交证件照
									<span style="color:red">JPG,PNG</span>文件
								</span>
							</a-form-item>
						</a-col>
					</a-row>
				</a-col>
				<a-col :span="8">
					<a-form-item label="&nbsp;">
						<a-button danger @click="deleteProject(index)">
							<delete-outlined />
						</a-button>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="20">
				<a-col :span="24" class="py-4 text-center">
					<a-space>
						<a-button class="cache-btn" @click="handleCache">
							<DeliveredProcedureOutlined />暂存
						</a-button>
						<a-button type="primary" html-type="submit">
							<save-outlined />保存
						</a-button>
						<a-button @click="closeTab('/consignor')">
							<close-outlined />关闭
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-form>
	</div>
</template>
<script setup>
import { computed, getCurrentInstance, inject, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { CloseOutlined, DeleteOutlined, DeliveredProcedureOutlined, ImportOutlined, LoadingOutlined, SaveOutlined } from "@ant-design/icons-vue";
import { post, get } from "@/utils/index.js";
import { baseURL } from "@/utils/request.js";
const { proxy } = getCurrentInstance();
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
const formRef = ref();
const formState = ref({
	status: 1,
	projects: []
});
const isSupplier = ref(false);
if (!id.value) {
	formState.value.password = "wtr123456";
}
const projectOptions = ref([]);
post("department/projects?type=3", { page_size: 1000 }).then(({ data }) => {
	projectOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const supplierOptions = ref([]);
post("user", { is_supplier: 1, page_size: Infinity }).then(({ data }) => {
	supplierOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.company_name || d.mobile,

			major: d.major
		};
	});
});
const addProject = () => {
	formState.value.projects.push({
		project_id: null,
		is_permanent: 0,
		fileUploading: false,
		date_range: []
	});
};
const deleteProject = index => {
	formState.value.projects.splice(index, 1);
};
const changeMobile = mobile => {
	formState.value.username = mobile;
};
const formRules = computed(() => {
	// const { id, password } = formState.value;
	return {
		fullname: [{ required: true, message: "请输入姓名", trigger: "blur" }],
		mobile: [
			{ required: true, message: "请输入用户手机号", trigger: "blur" },
			{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码" }
		],
		// password: [{ required: !id ? true : false, message: "请输入密码", trigger: "blur" }],
		//
		// confirm_password: [{
		// 	required: !id ? true : !!password,
		// 	trigger: "blur",
		// 	validator: (rule, value) => {
		// 		if (!id && !value) return Promise.reject("请输入确认密码");
		// 		if (value !== password) return Promise.reject("确认密码不一致");
		// 		return Promise.resolve();
		// 	}
		// }],
		status: [{ required: true, message: "请选择账户状态", trigger: "blur" }],
		parent_id: [{ required: true, message: "请选择供应商", trigger: "blur" }]
	};
});
const changePermanent = (item, index) => {
	if (item.is_permanent === 1) {
		formRef.value.resetFields([["projects", index, "date_range"]]);
	}
};
const beforeFileUpload = project => {
	return file => {
		project.fileUploading = true;
		if (!["image/png", "image/jpeg", "application/pdf"].includes(file.type)) {
			proxy.$message.error("只能上传照片或PDF文件");
			project.fileUploading = false;
			return false;
		}
		const isLt10M = file.size / 1024 / 1024 < 10;
		if (!isLt10M) {
			proxy.$message.error("只能上传10MB以下文件");
			project.fileUploading = false;
			return false;
		}
	};
};
const changeFileUpload = (project, { file }) => {
	if (file.status === "done") {
		project.entrust_file_path = [
			{
				name: file.name,
				url: file.response.data.url
			}
		];
		project.fileUploading = false;
		proxy.$message.success("上传成功");
	}
	if (!file.status) {
		project.entrust_file_path = project.entrust_file_path.filter(item => item.url);
	}
};
const changeDateRange = record => {
	if (!record.date_range.length) return;

	for (const project of formState.value.projects) {
		if (!supplierInfo.value.value) {
			proxy.$message.error(`请先选择供应商`);
			record.date_range = [];
			return;
		}

		continue;

		if (project.project_id === record.project_id) continue;

		//1劳务作业，2专业作业不允许授权有效期重叠
		if (!/,(1|2),/.test(`,${supplierInfo.value.major},`)) continue;

		if (record.date_range[0] <= project.date_range[1] && record.date_range[0] >= project.date_range[0]) {
			proxy.$message.error(`与${projectOptions.value.find(item => item.value === project.project_id)?.label}授权有效期范围重叠`);
			record.date_range = [];
			return;
		}
		if (record.date_range[1] <= project.date_range[1] && record.date_range[1] >= project.date_range[0]) {
			proxy.$message.error(`与${projectOptions.value.find(item => item.value === project.project_id)?.label}授权有效期范围重叠`);
			record.date_range = [];
			return;
		}
	}
};
onMounted(async () => {
	const cacheData = localStorage.getItem("consignor-save");
	formState.value = JSON.parse(cacheData) || formState.value;
	if (id.value) {
		await get("user/info", { id: id.value }).then(async data => {
			delete data.password;
			formState.value = data;
			formState.value.projects = [];
			if (formState.value.is_supplier) {
				isSupplier.value = true;
			}
			for (const department of data.departments) {
				formState.value.projects.push({
					project_id: department.id,
					is_permanent: department?.UserDepartment?.is_permanent,
					date_range: department?.UserDepartment?.is_permanent ? [] : [department.UserDepartment.start_validity, department.UserDepartment.end_validity],
					entrust_file_path: department.UserDepartment.entrust_file_path ? [{ name: "委托书", url: department.UserDepartment.entrust_file_path }] : null
				});
			}

			//获取供应商信息
			supplierInfo.value = await get("user/info", { id: data.parent_id }).then(({ id: value, company_name, mobile, major }) => {
				return {
					value,
					label: company_name || mobile,
					major
				};
			});
		});
	} else {
		if (!cacheData) {
			addProject();
		}
	}
});
const changeProject = project => {
	const projectCount = formState.value.projects.filter(item => item.project_id === project.project_id).length;
	if (projectCount > 1) {
		proxy.$message.error("项目已存在，请重新选择");
		project.project_id = null;
	}
};
const save = () => {
	formRef.value.validate().then(() => {
		proxy.$message.destroy();
		const params = {
			...JSON.parse(JSON.stringify(formState.value)),
			is_consignor: 1,
			role_id: 55 // 委托人角色
		};
		params.username = params.mobile;
		delete params.certificate_file_path;
		delete params.password;
		if (!params.projects.length) {
			return proxy.$message.error("委托人至少要绑定一个项目");
		}
		for (const project of params.projects) {
			project.entrust_file_path = project.entrust_file_path[0]?.url;
		}
		params.projects = JSON.stringify(params.projects);
		post("user/save", params)
			.then(() => {
				proxy.$message.success("委托人提交成功", 1);
				closeTab("/consignor");
				localStorage.removeItem("consignor-save");
			})
			.catch(err => {
				proxy.$message.error(err);
			});
	});
};
const handleCache = () => {
	localStorage.setItem("consignor-save", JSON.stringify(formState.value));
	proxy.$message.success("缓存成功");
};
const closeTab = inject("closeTab");

const supplierInfo = ref({});
const changeSupplier = e => {
	supplierInfo.value = supplierOptions.value.find(d => d.value === e);
};
</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;

	h2 {
		font-size: 16px;
		font-weight: 600;
		line-height: 30px;
		margin-bottom: 20px;
	}
}

:deep(.ant-table-cell) .ant-form-item {
	margin-bottom: 0;

	.ant-form-item-explain {
		position: absolute;
		bottom: -24px;
	}
}

.cache-btn {
	background-color: #0d9424;
	color: #fff;
}
</style>